package com.crm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.mapper.BusinessMapper;
import com.crm.pojo.common.UserContext;
import com.crm.pojo.domain.Business;
import com.crm.pojo.domain.User;
import com.crm.service.BusinessService;
import com.crm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: xaw
 * @CreateTime: 2025-09-05  16:04:59
 * @Description:
 * @Version: 1.0
 */
@Slf4j
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    
    private final UserService userService;
    
    public BusinessServiceImpl(UserService userService) {
        this.userService = userService;
    }
    
    @Override
    public String getLatestNextTime(Integer businessId) {
        // 首先从business表中获取next_time字段
        Business business = this.getById(businessId);
        if (business != null && business.getNextTime() != null) {
            return business.getNextTime();
        }
        
        // 如果business表中没有next_time，则从business_record表中获取最新的记录
        return this.baseMapper.getLatestNextTime(businessId);
    }
    
    @Override
    public boolean gainBusinesses(String ids, Long userId) {
        // 将逗号分隔的ID字符串转换为List
        List<Integer> idList = Arrays.stream(ids.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        
        // 获取用户昵称
        String userNickName = "";
        // 修复：使用正确的用户查询方法
        User user = userService.getUserById(userId.intValue());
        if (user != null) {
            userNickName = user.getNickName();
        }
        
        // 批量更新商机状态
        String finalUserNickName = userNickName;
        return this.updateBatchById(idList.stream().map(id -> {
            Business business = new Business();
            business.setId(id);
            business.setIsPool(0); // 设置为非公海池状态
            business.setStatus(1); // 设置状态为"待跟进"
            business.setOwner(UserContext.getCurrentUser().getUserName()); // 设置归属人
            return business;
        }).collect(Collectors.toList()));
    }
    
    @Override
    public boolean backToPool(Integer businessId, String reason) {
        try {
            Business business = new Business();
            business.setId(businessId);
            business.setIsPool(1); // 设置为公海池状态
            business.setReasons(reason); // 设置退回原因
            business.setOwner(""); // 清除归属人
            return this.updateById(business);
        } catch (Exception e) {
            log.error("退回公海异常, businessId: {}, reason: {}", businessId, reason, e);
            return false;
        }
    }
    
    @Override
    public boolean assignBusinesses(String ids, Long userId) {
        // 将逗号分隔的ID字符串转换为List
        List<Integer> idList = Arrays.stream(ids.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        
        // 获取用户昵称
        String userNickName = "";
        // 修复：使用正确的用户查询方法
        User user = userService.getUserById(userId.intValue());
        if (user != null) {
            userNickName = user.getNickName();
        }
        
        // 批量更新商机状态
        String finalUserNickName = userNickName;
        return this.updateBatchById(idList.stream().map(id -> {
            Business business = new Business();
            business.setId(id);
            business.setIsPool(0); // 设置为非公海池状态
            business.setStatus(0); // 设置状态为"待跟进"
            business.setOwner(finalUserNickName); // 设置归属人
            return business;
        }).collect(Collectors.toList()));
    }
}